import React, { Component } from "react";
import { Card, Button, Table, message, Modal, Input, Select, Form } from "antd";
import { reqUserList } from "../../api/index";
import LinkButton from "../../component/LinkButton";
import { reqAddUser, reqDelUser, reqUpdateUser } from "../../api/index";
const { Option } = Select;
//USer组件
export default class User extends Component {
  state = {
    userList: [],
    roleList: [],
    visible: false,
    username: "",
    password: "",
    phone: "",
    email: "",
    role: "5ed84f50ea653837f91ab4cf",
    _id: "",
    flag: "添加用户",
  };
  UNSAFE_componentWillMount() {
    //获取用户列表o
    this.getUserList();
    //form数据
  }
  //获取userList的函数
  getUserList = async () => {
    const res = await reqUserList();
    if (res.status !== 0) {
      message.error("获取用户列表失败");
    }
    this.setState({
      userList: res.data.users,
      roleList: res.data.roles,
    });
  };
  //根据ID获取role角色
  getRoleById = (id) => {
    let role = "";
    this.state.roleList.forEach((item) => {
      if (item._id === id) {
        role = item.name;
        return;
      }
    });
    return role;
  };
  //用户更新
  handleUpdate = (data) => {
    console.log(data);
    this.setState({
      username: data.username,
      password: data.password,
      phone: data.phone,
      email: data.email,
      role: data.role_id,
      _id: data._id,
      visible: true,
      flag: "修改用户",
    });
  };
  //提交表单
  handleOk = async () => {
    const { username, password, phone, email, role, _id } = this.state;
    if (!username || !password || !phone || !email || !role) {
      message.warning("请完整填写表单项");
      return;
    }
    if (this.state.flag === "添加用户") {
      const res = await reqAddUser({
        username,
        password,
        phone,
        email,
        role_id: role,
      });
      if (res.status !== 0) {
        message.error("添加用户失败");
      } else {
        message.success("添加用户成功");
      }
    } else {
      const res = await reqUpdateUser({
        username,
        password,
        phone,
        email,
        role_id: role,
        _id,
      });
      if (res.status !== 0) {
        message.error("修改用户失败");
      } else {
        message.success("修改用户成功");
        this.setState({ flag: "添加用户" });
      }
    }
    this.setState({
      visible: false,
      username: "",
      password: "",
      phone: "",
      email: "",
      role: "5ed84f50ea653837f91ab4cf",
    });
    this.getUserList();
  };
  //handelAdd
  handleAdd = (e, cas) => {
    switch (cas) {
      case "username":
        this.setState({ username: e.target.value });

        break;
      case "password":
        this.setState({ password: e.target.value });
        break;
      case "phone":
        this.setState({ phone: e.target.value });

        break;
      case "email":
        this.setState({ email: e.target.value });

        break;
      case "role":
        this.setState({ role: e });
        break;
      default:
        console.log("happy ");
    }
  };
  handleCancel = () => {
    console.log("Clicked cancel button");
    this.setState({
      visible: false,
    });
  };
  //添加用户按钮事件
  handleAddUser = () => {
    this.setState({
      visible: true,
    });
  };
  //处理删除用户
  handleDel = async (id) => {
    const res = await reqDelUser(id);
    if (res.status !== 0) {
      message.error("删除用户失败");
    } else {
      message.success("删除用户成功");
      this.getUserList();
    }
  };
  render() {
    //state解构
    const { userList, visible } = this.state;
    //card 的 题目 常量
    const title = (
      <Button type="primary" onClick={this.handleAddUser}>
        创建用户
      </Button>
    );
    //Table 配置信息
    const dataSource = userList;

    const columns = [
      {
        title: "用户名",
        dataIndex: "username",
        width: 160,
      },
      {
        title: "邮箱",
        dataIndex: "email",
      },
      {
        title: "电话",
        dataIndex: "phone",
      },
      {
        title: "注册时间",
        dataIndex: "create_time",
      },
      {
        title: "所属角色",
        dataIndex: "role_id",
        render: (id) => this.getRoleById(id),
      },
      {
        title: "操作",
        dataIndex: "_id",
        render: (id, data) => {
          return (
            <span>
              <LinkButton
                onClick={() => {
                  this.handleUpdate(data);
                }}
              >
                修改
              </LinkButton>
              <LinkButton
                onClick={() => {
                  this.handleDel(id);
                }}
              >
                删除
              </LinkButton>
            </span>
          );
        },
      },
    ];
    const layout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
    };

    return (
      <Card title={title}>
        {/* 表单 */}
        <Modal
          title={this.state.flag}
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form {...layout}>
            <Form.Item label="用户名">
              <Input
                placeholder="请输入用户名"
                onChange={(e) => {
                  this.handleAdd(e, "username");
                }}
                value={this.state.username}
              ></Input>
            </Form.Item>
            <Form.Item label="密码">
              <Input
                type="password"
                placeholder="请输入密码"
                onChange={(e) => {
                  this.handleAdd(e, "password");
                }}
                value={this.state.password}
              ></Input>
            </Form.Item>
            <Form.Item label="手机号">
              <Input
                placeholder="请输入手机号"
                onChange={(e) => {
                  this.handleAdd(e, "phone");
                }}
                value={this.state.phone}
              ></Input>
            </Form.Item>
            <Form.Item label="邮箱">
              <Input
                placeholder="请输入邮箱"
                onChange={(e) => {
                  this.handleAdd(e, "email");
                }}
                value={this.state.email}
              ></Input>
            </Form.Item>
            <Form.Item label="角色">
              <Select
                showSearch
                placeholder="请选择角色"
                value={this.state.role}
                defaultValue="5ed84f50ea653837f91ab4cf"
                style={{ width: 120 }}
                onChange={(e) => {
                  this.handleAdd(e, "role");
                }}
              >
                {this.state.roleList.map((item) => {
                  return (
                    <Option value={item._id} key={item._id}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Form>
        </Modal>
        {/* 表格 */}
        <Table
          bordered
          dataSource={dataSource}
          columns={columns}
          rowKey="_id"
          pagination={{
            pageSize: 5,
          }}
        />
      </Card>
    );
  }
}
